<template>
  <div class="box">
    <div class="part">
      <ChartSearch
        ref="ylSearchRef"
        :company="companys['1']"
        :type="1"
        @onSubmit="onSearchSubmit"
      />
      <div ref="ylRef" class="column"></div>
    </div>
    <div class="part">
      <ChartSearch
        ref="zsSearchRef"
        :company="companys['2']"
        :type="1"
        @onSubmit="onSearchSubmit"
      />
      <div ref="zsRef" class="column"></div>
    </div>
    <div class="part">
      <ChartSearch
        ref="mzdSearchRef"
        :company="companys['3']"
        :type="1"
        @onSubmit="onSearchSubmit"
      />
      <div ref="mzdRef" class="column"></div>
    </div>
    <div class="part">
      <div class="column">
        <div class="head">
          <a-select
            :options="yearOpts"
            v-model:value="state.year"
            size="small"
          ></a-select>
        </div>
        <div class="chart">
          <div class="ratio">
            <div class="tip">指标完成率</div>
            <div ref="pieRef" class="pie"></div>
          </div>
          <div ref="watchRef" class="watch"></div>
        </div>
      </div>
      <div class="abnormal">
        <Abnormal />
      </div>
    </div>
  </div>
</template>
<script setup>
import { getCurrentInstance, reactive, ref, onMounted, watch } from "vue";
import * as echarts from "echarts";
import _ from "lodash";
import ChartSearch from "@/components/ChartSearch.vue";
import { companys } from "@/utils/source";
import dayjs from "dayjs";
import Abnormal from "@/components/Abnormal.vue";

const year = dayjs().year();
const yearOpts = [];
for (let i = 0; i < 20; i++) {
  const _year = year - i;
  yearOpts.push({ label: `${_year}年`, value: _year });
}

const state = reactive({
  year: null,
});

const { proxy } = getCurrentInstance();
const ylRef = ref();
const ylSearchRef = ref();
const zsRef = ref();
const zsSearchRef = ref();
const mzdRef = ref();
const mzdSearchRef = ref();

const pieRef = ref();
const watchRef = ref();

let ylChart, zsChart, mzdChart, pieChart, watchChart;
onMounted(() => {
  ylChart = echarts.init(ylRef.value);
  ylSearchRef.value.submit();

  zsChart = echarts.init(zsRef.value);
  zsSearchRef.value.submit();

  mzdChart = echarts.init(mzdRef.value);
  mzdSearchRef.value.submit();

  pieChart = echarts.init(pieRef.value);
  watchChart = echarts.init(watchRef.value);

  state.year = year;
  // 监听窗口大小变化
  window.addEventListener("resize", function () {
    // 当窗口大小变化时，重新设置图表的大小
    pieChart.resize();
    watchChart.resize();
    ylChart.resize();
    zsChart.resize();
    mzdChart.resize();
  });
});

// 数据查询
const onSearchSubmit = async (obj) => {
  const { company, category, type, method, dateType, start, end } = obj;
  let chart = null;
  if (company === companys["1"]) {
    chart = ylChart;
  } else if (company === companys["2"]) {
    chart = zsChart;
  } else if (company === companys["3"]) {
    chart = mzdChart;
  }
  let beginTime, endTime;
  if (start) {
    beginTime = start.format("YYYY-MM");
  }
  if (end) {
    endTime = end.format("YYYY-MM");
  }
  if (chart) {
    const moment = dayjs();

    const query = { company, year: moment.year(), type, beginTime, endTime };
    // 获取数据
    const { success, data } = await proxy.$axios.get("/energy_monitor/list2", {
      params: query,
    });
    if (success && data.length) {
      const db = _.map(data, (yearDB) => {
        const list = _.map(yearDB.list, (o) => {
          let months = null,
            unit = null;
          if (method === "1") {
            // 碳排放量
            months = _.map(o.months, (m) => m * o.factor * o.ratio);
            unit = "t";
          } else {
            // 实物量
            months = o.months;
            unit = o.unit;
          }
          return { name: o.name, sum: _.sum(months), unit, months };
        });
        // 碳排放量追加一行“总量”数据
        if (method === "1") {
          const months = [];
          for (let i = 0; i < 12; i++) {
            const allByMonth = _.map(list, ({ months }) => months[i]);
            months.push(_.sum(allByMonth));
          }
          list.push({
            name: "碳排总量",
            sum: _.sum(months),
            unit: "t",
            months,
          });
        }
        return { ...yearDB, list };
      });

      const xAxis = [];
      let source = [];
      let unit = "";

      if (dateType === "other") {
        // 可能跨年
        if (start && end) {
          // 按照月度范围传值
          query.start = start.format("YYYY-MM");
          query.end = end.format("YYYY-MM");
          const diff = end.diff(start, "month");
          for (let i = 0; i <= diff; i++) {
            // 某个月度dayjs形式
            const month = start.add(i, "month");
            // 查询某月索引
            const index = month.month();
            // 查询某年数字
            const the = _.find(db, { year: month.year() });
            const one = _.find(the.list, { name: category });
            let v = 0;
            if (one) {
              v = one.months[index];
              // 记录单位（同一种能源单位一致，所以无所谓覆盖）
              unit = one.unit;
            }
            source.push(v);
            xAxis.push(month.format("YYYY-MM"));
          }
        }
      } else {
        // 当前年度
        const the = _.find(db, { year: query.year });
        const one = _.find(the.list, { name: category });
        if (one) {
          // 实物量
          source = one.months;
          // 实物量则按照能源种类的单位
          unit = one.unit;
        }

        if (dateType === "month") {
          //月度
          const start = moment.startOf("year");
          for (let i = 0; i < 12; i++) {
            xAxis.push(start.add(i, "month").format("YYYY-MM"));
          }
        } else if (dateType === "quarter") {
          // 季度
          let arr = [];
          for (let i = 1; i <= 4; i++) {
            xAxis.push(`${i}季度`);
            arr.push(_.sum(source.slice((i - 1) * 3, i * 3)));
          }
          source = arr;
        } else if (dateType === "year") {
          // 年度
          const year = moment.year();
          xAxis.push(year);

          source = [_.sum(source)];
        }
      }

      chart.setOption({
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999",
            },
          },
          valueFormatter: (value) => `${value.toFixed(2)}(${unit})`,
        },
        xAxis: {
          data: xAxis,
          axisPointer: {
            type: "shadow",
          },
        },
        yAxis: [
          {
            type: "value",
            axisLabel: {
              formatter: `{value} ${unit}`,
            },
          },
        ],
        legend: {
          textStyle: { color: "#fff" },
          bottom: 10,
          left: "center",
          icon: "circle",
        },
        series: [
          {
            type: "bar",
            barWidth: 30,
            data: source,
          },
        ],
      });
    }
  }
};

watch(
  () => state.year,
  (_year) => {
    proxy.$axios
      .get("/energy_monitor/c_complete_rate_quote", { params: { year: _year } })
      .then(({ success, data }) => {
        if (success) {
          const c_complete_rate = data.c_complete_rate || 0;
          pieChart.setOption({
            grid: {
              top: "10px",
              left: "10px",
              right: "10px",
              bottom: "10px",
            },
            tooltip: {
              formatter: "{a} <br/>{b} : {c}%",
            },
            series: [
              {
                name: "完成率",
                type: "gauge",
                radius: "90%",
                progress: {
                  show: true,
                },
                axisTick: {
                  show: false, // 不显示刻度
                },
                axisLabel: {
                  show: false, // 不显示刻度标签
                },
                splitLine: {
                  show: false,
                },
                detail: {
                  show: true, // 不显示数据细节
                  fontSize: 12,
                  formatter: "{value}%",
                  color: "#fff",
                },
                title: { show: true, fontSize: 12, color: "#fff" },
                data: [
                  {
                    value: (c_complete_rate * 100).toFixed(2),
                    name: "孖洲岛",
                  },
                ],
              },
            ],
          });

          const _o = data["碳排放强度-因子指标"];
          const months = _o?.months || [];
          const avg = data?.name_c_power_flag_include || 0;
          watchChart.setOption({
            title: {
              left: "center",
              top: 10,
              text: "孖洲岛碳排放强度监控",
              textStyle: { fontSize: 12, color: "#fff" },
            },
            tooltip: {
              trigger: "axis",
            },
            grid: {
              top: "20%",
              left: "10%",
              right: "10%",
              bottom: "15%",
            },
            xAxis: {
              type: "category",
              data: [
                "1月",
                "2月",
                "3月",
                "4月",
                "5月",
                "6月",
                "7月",
                "8月",
                "9月",
                "10月",
                "11月",
                "12月",
              ],
            },
            yAxis: {
              type: "value",
            },
            series: [
              {
                data: _.map(months, (o) => o.toFixed(4)),
                type: "bar",
                markLine: {
                  symbol: "none",
                  data: [
                    {
                      name: "指标值",
                      yAxis: avg,
                      label: { formatter: "{b}:{c}", offset: [-30, 0] },
                    },
                  ],
                },
              },
            ],
          });
        }
      });
  }
);
</script>
<style lang="less" scoped>
.box {
  padding: 5px;
  height: 100%;
  display: flex;
  flex-wrap: wrap;

  .part {
    width: 50%;
    height: 50%;
    border: 1px solid #f8f8f8;
    display: flex;
    flex-direction: column;

    .column {
      flex: 1;

      .head {
        height: 20px;
        text-align: right;
        padding: 8px;
      }

      .chart {
        height: calc(100% - 20px);
        display: flex;
        align-items: center;

        .ratio {
          width: 30%;
          height: 100%;
          display: flex;
          flex-direction: column;

          .tip {
            width: 100%;
            color: #fff;
            padding-top: 5px;
            font-weight: 400;
            text-align: center;
          }

          .pie {
            flex: 1;
          }
        }

        .watch {
          width: 70%;
          height: 100%;
        }
      }
    }

    .abnormal {
      height: 110px;
    }
  }
}
</style>
